package com.tsd.system.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.core.constants.Constants;
import com.tsd.core.constants.VersionConstants;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.version.VersionUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.system.entity.*;
import com.tsd.system.service.SysGroupRoleResourceService;
import com.tsd.system.service.SysResourceService;
import com.tsd.system.service.SysUserResourceService;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：SysUserResource 控制层
 *
 * @author Hillpool
 * @date 2019/03/12 12:20:51
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
public class SysUserResourceController extends SystemBaseController {

    @Resource
    private SysUserResourceService sysUserResourceService;
    @Resource
    private SysResourceService sysResourceService;
    @Resource
    private SysGroupRoleResourceService sysGroupRoleResourceService;


    @ApiOperation(value = "根据id查询用户资源")
    @ResponseBody
    @RequestMapping(value = "/getSysUserResourceById.action", method = RequestMethod.POST)
    public HttpResult<SysUserResource> getSysUserResourceById() {
        HttpResult<SysUserResource> hr = new HttpResult<SysUserResource>();
        try {
            Map<String, Object> map = super.getParams(request);
            Long id = (Long) map.get("id");
            super.checkEmpty(id, "请提供参数id");
            SysUserResource sysUserResource = sysUserResourceService.getSysUserResourceById(id);
            hr.setData(sysUserResource);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "保存用户资源")
    @ResponseBody
    @RequestMapping(value = "/saveSysUserResource.action", method = RequestMethod.POST)
    public HttpResult<String> saveSysUserResource() {
        HttpResult<String> hr = new HttpResult<String>();
        try {
            Map<String, Object> map = super.getParams(request);
            SysUserResource t = JSON.parseObject(JSON.toJSONString(map), SysUserResource.class);
            sysUserResourceService.saveSysUserResource(t);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除用户资源")
    @ResponseBody
    @RequestMapping(value = "/deleteSysUserResource.action", method = RequestMethod.POST)
    public HttpResult<String> deleteSysUserResource() {
        HttpResult<String> hr = new HttpResult<String>();
        try {
            Map<String, Object> map = super.getParams(request);
            SysUser sysUser = this.getSysUser();
            String userId = HlpUtils.getString(map, "userId");
            String json = JSON.toJSONString(map.get("resourceIdList"));
            List<String> resourceIdList = JSON.parseArray(json, String.class);
            sysUserResourceService.deleteSysUserResource(sysUser, userId, resourceIdList);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询用户资源")
    @ResponseBody
    @RequestMapping(value = "/findSysUserResources.action", method = RequestMethod.POST)
    public HttpResult<List<SysUserResourceExt>> findSysUserResources() {
        HttpResult<List<SysUserResourceExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<String, Object>();
            //String searchValue = (String) map.get("searchValue");
            //if (!HlpUtils.isEmpty(searchValue)) {
            //	params.put("searchValue", "%" + searchValue + "%");
            //}
            PageBean page = new PageBean(map);
            List<SysUserResourceExt> list = sysUserResourceService.findSysUserResources(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "设置用户拥有的资源列表")
    @ResponseBody
    @RequestMapping(value = "/saveResourceList2User.action", method = RequestMethod.POST)
    public HttpResult<SysResource> saveResourceList2User() {
        HttpResult<SysResource> hr = new HttpResult<SysResource>();
        try {
            Map<String, Object> map = super.getParams(request);
            SysUser opUser = super.getSysUser();
            String userId = HlpUtils.getString(map, "userSid");
            String json = HlpUtils.getString(map, "resourceIdList");
            List<String> resourceIdList = JSON.parseArray(json, String.class);
            //2020-04-16 修改用户授权为同一个单位的同一个角色的权限共用
            sysGroupRoleResourceService.saveSysResourceList2GroupRole(opUser, userId, resourceIdList);
//            sysUserResourceService.saveSysResourceList2User(opUser, userId, resourceIdList);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "获取用户拥有的资源")
    @ResponseBody
    @RequestMapping(value = "/findResource4User.action", method = RequestMethod.POST)
    public HttpResult<Object> findResource4User() {
        HttpResult<Object> hr = new HttpResult<Object>();
        try {
            SysUser opUser = this.getSysUser();
            Map<String, Object> map = this.getParams(request);
            String userId = HlpUtils.getString(map, "userId");
            List<SysResourceExt> list = sysResourceService.findSysResource4User(userId);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "获取当前登录用户拥有的资源树")
    @ResponseBody
    @RequestMapping(value = "/findResourceTree4User.action", method = RequestMethod.POST)
    public HttpResult<Object> findResourceTree4User() {
        HttpResult<Object> hr = new HttpResult<Object>();
        try {
            SysUser opUser = this.getSysUser();
            Map<String, Object> map = this.getParams(request);
            Object parent_code = map.get("parent_code");
            List<String> parentCodelist = JSON.parseArray(parent_code == null ? "[-1]" : JSON.toJSONString(parent_code), String.class);
            List<SysResourceExt> list = sysUserResourceService.queryTree4UserIdRole(parentCodelist, opUser.getSid());
//            List<SysResourceExt> list = sysUserResourceService.queryTree4UserIdNew(parent_code, opUser.getSid());
            setResourceVersion(list);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    private void setResourceVersion(List<SysResourceExt> list) {
        if (!HlpUtils.isEmptyList(list)) {
            for (SysResourceExt resourceExt : list) {
                String ver = VersionUtil.verifyVersion(resourceExt.getTarget_url());
                if (ver != null) {
                    resourceExt.setMin_ver(VersionConstants.getVersionValue(ver));
                }
                if (!HlpUtils.isEmptyList(resourceExt.getChildrens())) {
                    setResourceVersion(resourceExt.getChildrens());
                }
            }
        }
    }

    @ApiOperation(value = "获取指定用户拥有的资源树")
    @ResponseBody
    @RequestMapping(value = "/findResourceTreeByUserId.action", method = RequestMethod.POST)
    public HttpResult<Object> findResourceTreeByUserId() {
        HttpResult<Object> hr = new HttpResult<Object>();
        try {
            Map<String, Object> map = super.getParams(request);
            SysUser opUser = super.getSysUser();
            String userId = HlpUtils.getString(map, "userId");
            if (HlpUtils.isEmpty(userId)) {
                userId = opUser.getSid();
            }
            String needTag = HlpUtils.getString(map, "needTag");
            List<SysResourceExt> list = sysUserResourceService.queryTree4UserId(Constants.ROOT_PARENT_SID, userId);
            if ("0".equals(needTag)) {
                hr.setData(list);
            } else {
                Map<String, List<SysResourceExt>> adjustedMap = new HashMap<>();
                for (SysResourceExt t : list) {
                    String key = t.getTag();
                    List<SysResourceExt> newList = adjustedMap.get(key);
                    if (newList == null) {
                        newList = new ArrayList<>();
                        adjustedMap.put(key, newList);
                    }
                    newList.add(t);
                }
                hr.setData(adjustedMap);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
